package com.oj.auth.entity;

import com.oj.api.auth.domain.AccountInfo;
import com.oj.api.auth.domain.RoleInfo;
import com.oj.api.auth.domain.UserGroupInfo;
import com.oj.common.data.BaseEntity;
import lombok.*;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 系统账号实体
 * Created by Bing on 2018/5/4.
 */
@Entity(name = "AUTH_ACCOUNT")
@Table(indexes = {
        @Index(name = "auth_idx_code_account", columnList = "code")
})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class AccountEntity extends BaseEntity<AccountInfo> {

    String password, mobile, email, studentNumber, SchoolName;

    /**
     * 用户组
     */
    @ManyToMany(mappedBy = "users",fetch = FetchType.LAZY)
    private Set<UserGroupEntity> userGroups;

   /**
     * 角色组
     */
    @ManyToMany(mappedBy = "users",fetch = FetchType.LAZY)
    private Set<RoleEntity> roles;

    @Override
    protected AccountInfo createInfo() {
        return new AccountInfo();
    }

    @Override
    public AccountInfo buildInfo(AccountInfo accountInfo) {
        super.buildInfo(accountInfo);
        List<RoleInfo> roleInfos = new ArrayList<>();
        List<UserGroupInfo> userGroupInfos = new ArrayList<>();
        if(this.roles!=null){
            this.roles.forEach(r->{
                roleInfos.add(r.buildInfo());
            });
        }
        if(this.userGroups!=null){
            StringBuilder sb = new StringBuilder();
            this.userGroups.forEach(u->{
                userGroupInfos.add(u.buildInfo());
                if(u.getProblemSetCodes()!=null){
                    String[] codes = u.getProblemSetCodes().split(",");
                    for(String code : codes){
                        sb.append(code.split("-")[0]+",");
                    }
                }

            });
            if(sb.length()>0){
                accountInfo.setProblemSetCodes(sb.toString().substring(0,sb.length()-1));
            }
        }
        accountInfo.setUserGroups(userGroupInfos);
        accountInfo.setRoles(roleInfos);
        return accountInfo;
    }
}
